package com.chen.controller;

import cn.hutool.core.map.MapUtil;
import com.chen.service.LoginService;
import com.chen.vo.Result;
import com.chen.vo.param.LoginParam;
import com.google.code.kaptcha.Producer;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.UUID;
import javax.imageio.ImageIO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

/**
 * @Author:chenao
 * @DATE:2022/3/10 22:33
 */
@RestController
public class LoginController {

    @Autowired
    private Producer producer;
    @Autowired
    private LoginService loginService;

    @PostMapping("login")
    public Result login(@RequestBody LoginParam param){
        return loginService.login(param);
    }

    @PostMapping("getcode")
    public Result getcode() throws IOException {

        String key = UUID.randomUUID().toString();
        String code = producer.createText();

        // 为了测试
//		key = "aaaaa";
//		code = "11111";

        //转换为64位编码
        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);

        BASE64Encoder encoder = new BASE64Encoder();
        String str = "data:image/jpeg;base64,";

        String base64Img = str + encoder.encode(outputStream.toByteArray());

        //存入Redis中
//        redisUtil.hset(Const.CAPTCHA_KEY, key, code, 120);
        return Result.success(
                MapUtil.builder()
                        .put("key", key)
                        .put("codeimg", base64Img)
                        .build()
        );
    }
}
